package com.baosight.risk.service.xtaa.code.impl;

import com.baosight.risk.api.rire.RiwaRiskWaringService;
import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.base.entity.MultipleUpdateStatus;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.redis.BaseRedis;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.mapper.xtaa.code.XtaaCodeMapper;
import com.baosight.risk.mapper.xtaa.code.XtaaCodeTypeMapper;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @desc:
 * @author: CuiShiHao
 **/
@Service

public class XtaaCodeServiceImpl extends BaseServiceImpl<XtaaCode> implements IXtaaCodeService {

    @Autowired
    private XtaaCodeMapper xtaaCodeMapper;
    @Autowired
    private XtaaCodeTypeMapper codeTypeMapper;
    @Autowired
    private BaseRedis redis;

    @Autowired
    private RiwaRiskWaringService waringService;

    private String XTAA_CODE_KEY = "xtaa:code:key:";


    @Override
    public BaseMapper getMapper() {
        return xtaaCodeMapper;
    }

    /**
     * 根据字典类型获取字典详细数据 仅启用数据
     *
     * @param ddTypeCode 字典类型
     * @return List<XtaaCode> 字典详细数据
     */
    @Override
    public List<XtaaCode> selectDataByDDTypeCode(String ddTypeCode) {
        String key = XTAA_CODE_KEY + ddTypeCode;
        if (!redis.isKey(key)) {
            redis.setValue(key, xtaaCodeMapper.selectDataByDDTypeCode(ddTypeCode));
        }
        //return (List<XtaaCode>) redis.getValue(key);
        return xtaaCodeMapper.selectAllDataByDDTypeCode(ddTypeCode);
    }

    /**
     * 根据字典类型获取字典详细数据 全部数据
     *
     * @param ddTypeCode 字典类型
     * @return List<XtaaCode> 字典详细数据
     */
    @Override
    public List<XtaaCode> selectAllDataByDDTypeCode(String ddTypeCode) {
        return xtaaCodeMapper.selectAllDataByDDTypeCode(ddTypeCode);
    }

    /**
     * 根据字典类型获取字典详细数据 全部数据
     *
     * @param ddTypeCode 字典类型
     * @param parentID   父节点ID
     * @return List<XtaaCode> 字典详细数据
     */
    @Override
    public List<XtaaCode> selectLazyDataByCodeAndParent(String ddTypeCode, String parentID) {
        List<XtaaCode> list = xtaaCodeMapper.selectLazyDataByDDTypeCodeAndParentID(ddTypeCode, parentID);
        return list;
    }

    public List<XtaaCode> selectLazyRiskDataByCodeAndParent(String ddTypeCode, String parentID) {
        List<XtaaCode> list = xtaaCodeMapper.selectLazyRiskDataByDDTypeCodeAndParentID(ddTypeCode, parentID);
        return list;
    }



    /**
     * 过滤方法selectLazyDataByCodeAndParent返回的字典数据
     *
     * @param codeList 字典集合
     * @return List<XtaaCode> 字典详细数据
     */
    @Override
    public List<XtaaCode> codeFilter(List<XtaaCode> codeList) {
        List<XtaaCode> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -1);
        String acctYear = DateUtils.format(calendar.getTime(), "YYYY");

        // 获取当前登录人所在公司，近年来所有的披露报告指标
        List<ZbaaTarget> resultList = waringService.getTargetByImport(acctYear, getUser().getExt1(), "");

        //根据指标过滤，只展示有指标的节点
        if (CollectionUtils.isNotEmpty(resultList)) {
            for (XtaaCode xtaaCode : codeList) {
                for (ZbaaTarget zbaaTarget : resultList) {
                    if (xtaaCode.getDdCode().equals(zbaaTarget.getTargetType())) {
                        list.add(xtaaCode);
                        break;
                    }
                }
            }
        }

        return list;
    }

    /**
     * 根据字典类型获取字典详细数据,根据字典名称模糊查询
     *
     * @param ddTypeCode 字典类型
     * @param ddName     名称 模糊查询
     * @return
     */
    @Override
    public List<XtaaCode> selectDataByDDTypeCodeAndDDName(String ddTypeCode, String ddName) {
        List<XtaaCode> resultList = xtaaCodeMapper.selectDataByDDTypeCodeAndDDName(ddTypeCode, ddName);
        return resultList;
    }

    @Override
    public Integer insertCode(XtaaCode code) {
        redis.deleteList(XTAA_CODE_KEY);

        // 拼接pathCode
        String path = getCodePath(code);
        code.setPathCode(path);

        // 拼接pathLevel
        XtaaCode parentCode = this.get(code.getParentGuid());
        if (parentCode != null) {
            Short pathLevel = (short) (parentCode.getPathLevel() + 1);
            code.setPathLevel(pathLevel);
        } else {
            code.setPathLevel((short) 1);
        }
        return xtaaCodeMapper.insert(code);
    }


    /**
     * @description 递归添加字典pathCode
     * @author CuiShiHao
     * @date 2019/7/20
     */
    public String getCodePath(XtaaCode code) {
        String path = "";
        if ("0".equals(code.getParentGuid())) {
            return code.getDdCode();
        } else {
            XtaaCode parentCode = this.get(code.getParentGuid());
            path += getCodePath(parentCode) + "/" + code.getDdCode();
        }
        return path;
    }

    @Override
    public Integer deleteCode(String id) {
        XtaaCode code = xtaaCodeMapper.selectByPrimaryKey(id);
        if (null == code) {
            return null;
        }
        redis.deleteList(XTAA_CODE_KEY);
        return xtaaCodeMapper.deleteByPrimaryKey(id);
    }


    @Override
    public Integer updateCode(XtaaCode code) {
        redis.deleteList(XTAA_CODE_KEY);

        //先更新父节点信息，拼接pathCode
        String pathCode = getCodePath(code);
        code.setPathCode(pathCode);
        xtaaCodeMapper.updateByPrimaryKeySelective(code);

        //更新子节点的PathCode信息
        List<XtaaCode> resultList = selectAllSubsetByParentID(code.getId());
        if (resultList.size() != 0) {
            for (XtaaCode xtaaCode : resultList) {
                String path = getCodePath(xtaaCode);
                xtaaCode.setPathCode(path);
                xtaaCodeMapper.updateByPrimaryKeySelective(xtaaCode);
            }
        }

        return xtaaCodeMapper.updateByPrimaryKeySelective(code);
    }

    /**
     * 根据父节点id获取下级数据（仅子集）
     *
     * @param id 父节点id
     * @return List<XtaaCode> 子集详细数据
     */
    @Override
    public List<XtaaCode> selectSubsetByParentID(String id) {
        List<XtaaCode> list = xtaaCodeMapper.selectSubsetByParentID(id);
        return list;
    }

    /**
     * 根据父节点id获取全部子集数据（包含子集孙集）
     *
     * @param id 父节点id
     * @return
     */
    @Override
    public List<XtaaCode> selectAllSubsetByParentID(String id) {
        List<XtaaCode> list = xtaaCodeMapper.selectAllSubsetByParentID(id);
        return list;
    }

    /**
     * 根据编码名称获取下级数据（包含子集孙集）
     *
     * @param ddCode 编码名称
     * @return
     */
    @Override
    public List<XtaaCode> selectAllSubsetByDDCode(String ddCode) {
        List<XtaaCode> list = xtaaCodeMapper.selectAllSubsetByDDCode(ddCode);
        return list;
    }

    /**
     * 根据ID集合批量更新状态
     *
     * @param updateStatus
     * @return
     */
    @Override
    public Integer multipleUpdateStatus(MultipleUpdateStatus updateStatus) {
        if (updateStatus.getIds().size() == 0) {
            return 0;
        }
        XtaaCode code = xtaaCodeMapper.selectByPrimaryKey(updateStatus.getIds().get(0));
        if (null == code) {
            return 0;
        }
        redis.deleteList(XTAA_CODE_KEY);
        return xtaaCodeMapper.multipleUpdateStatus(updateStatus);
    }

    /**
     * 根据ID集合批量更新状态
     *
     * @param map
     * @return
     */
    @Override
    public Integer deleteByIds(Map<String, Object> map) {
        redis.deleteList(XTAA_CODE_KEY);
        return xtaaCodeMapper.deleteByIds(map);
    }

    /**
     * 根据字典名称和末级获取字典信息
     *
     * @return
     */
    @Override
    public XtaaCode selectXtaaCodeByDDCodeAndEndLevel(String DDCode) {
        return xtaaCodeMapper.selectXtaaCodeByDDCodeAndEndLevel(DDCode);
    }

    /**
     * 根据父节点ID获取字典信息
     *
     * @param ParentGuid 父节点ID
     * @return
     */
    @Override
    public XtaaCode selectXtaaCodeByParentGuid(String ParentGuid) {
        return xtaaCodeMapper.selectXtaaCodeByParentGuid(ParentGuid);
    }

    /**
     * 根据字典信息获取父节点编码
     *
     * @param xtaaCode 字典信息
     * @return
     */
    @Override
    public String selectParentXtaaCodeNameByXtaaCode(XtaaCode xtaaCode) {
        if ("0".equals(xtaaCode.getParentGuid())) {
            return xtaaCode.getDdCode();
        } else {
            XtaaCode parentXtaaCode = selectXtaaCodeByParentGuid(xtaaCode.getParentGuid());
            return selectParentXtaaCodeNameByXtaaCode(parentXtaaCode);
        }
    }

    @Override
    public List<XtaaCode> listByParentCode(String ddType, String parentCode) {
        List<XtaaCode> xtaaCodes = xtaaCodeMapper.listByParentCodeAndDDType(ddType, parentCode);
        return xtaaCodes;
    }
}
